import Layouts from '@/components/Layout';
import { Tabs, Typography, Select, Pagination, Empty, Spin } from 'antd';
import { UserOutlined, CarOutlined, TagsOutlined, GlobalOutlined } from '@ant-design/icons';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';
import FeedUser from '@/components/FeedUser';
import Activity from '@/components/Activity';
import { getUserList } from '@/service/api/user';
import { getType } from '@/service/api/common';
import { getCountriesList } from '@/service/api/location';
import type { UserInfo, UserInfoSearch } from '@/types/user';
import type { CommonData } from '@/types/common';
import type { CountriesList } from '@/types/loaction';
import { getActivityList } from '@/service/api/touractivity';
import { ActivityList, ActivitySearch } from '@/types/touractivity';
import { useLocation } from 'umi';
const Feed: React.FC = () => {
  const location = useLocation();
  const [listLoading, setListLoading] = useState<boolean>(false);
  const [tagsData, setTagsData] = useState<CommonData[]>([]);
  const [hobbySelectVal, setHobbySelectVal] = useState<string | null | undefined>(undefined);
  const [countriesData, setCountriesData] = useState<CountriesList[]>([]);
  const [userList, setUserList] = useState<UserInfo[]>([]);
  const [searchTourQuery, setSearchTourQuery] = useState<UserInfoSearch>({
    pageNum: 1,
    pageSize: 9,
    tags: location['query'].tag ?? null,
  });
  const [listTotal, setListTotal] = useState<number>(0);
  const [searchActivityQuery, setSearchActivityQuery] = useState<ActivitySearch>({
    pageNum: 1,
    pageSize: 9,
  });
  const [activityListData, setActivityListData] = useState<ActivityList[]>([]);
  const [activityTotal, setActivityTotal] = useState<number>(0);
  const [actListLoading, setActListLoading] = useState<boolean>(false);
  const firstUpload = useRef(true); // 记录是否是首次加载页面
  const handleChangePage = (page: number, pageSize: number) => {
    setSearchTourQuery({
      ...searchTourQuery,
      pageNum: page,
      pageSize,
    });
  };
  const handleChangePageAct = (page: number, pageSize: number) => {
    setSearchActivityQuery({
      pageNum: page,
      pageSize,
    });
  };
  const tagsChange = (value: string) => {
    setHobbySelectVal(value);
    setSearchTourQuery({
      ...searchTourQuery,
      tags: value,
    });
  };
  const countriesChange = (value: string) => {
    setSearchTourQuery({
      ...searchTourQuery,
      country: value,
    });
  };
  const onChange = (key: string) => {
    if (key === '1') {
      // setSearchTourQuery({
      //   ...searchTourQuery,
      //   country: value,
      // });
    } else if (key === '2') {
      setSearchActivityQuery((searchActivityQuery) => ({ ...searchActivityQuery, pageNum: 1 }));
    }
  };
  const getTagsData = async () => {
    const { data }: { data: CommonData[] } = await getType({
      dictType: 'adv_interest',
    });
    setTagsData(data);
  };
  const getCountryData = async () => {
    const { rows }: { rows: CountriesList[] } = await getCountriesList({
      pageNum: 1,
      pageSize: 240, // 全部国家列表
    });
    setCountriesData(rows);
  };
  const getUserListData = async () => {
    try {
      setListLoading(true);
      const { rows, total }: { rows: UserInfo[]; total: number } = await getUserList(
        searchTourQuery,
      );
      setUserList(rows);
      setListTotal(total);
    } finally {
      setListLoading(false);
    }
  };
  const getActivityListData = async () => {
    try {
      setActListLoading(true);
      const { rows, total }: { rows: ActivityList[]; total: number } = await getActivityList(
        searchActivityQuery,
      );
      setActivityListData(rows);
      setActivityTotal(total);
    } finally {
      setActListLoading(false);
    }
  };
  useEffect(() => {
    const { tag } = location['query'];
    getTagsData();
    getCountryData();
    if (tag) {
      let arr = [];
      arr.push(tag);
      setHobbySelectVal(arr.toString());
    }
  }, []);
  useEffect(() => {
    getUserListData();
  }, [searchTourQuery]);
  useEffect(() => {
    if (firstUpload.current) {
      // 首次加载不执行
      firstUpload.current = false;
      return;
    }
    getActivityListData();
  }, [searchActivityQuery]);
  const contentPanel1 = (
    <div className="feed_user_wrapper">
      <div className="filter_wrapper">
        <div className="filter_item">
          <div className="filter_type_tit">
            <Typography.Title level={5} style={{ margin: 0, fontWeight: 'normal' }}>
              <TagsOutlined style={{ marginRight: 8 }} />
              按兴趣查找社区成员：
            </Typography.Title>
          </div>
          <Select
            mode="tags"
            maxTagCount={5}
            style={{ flex: 1 }}
            placeholder="请选择标签"
            fieldNames={{ label: 'dictLabel', value: 'dictValue' }}
            onChange={tagsChange}
            options={tagsData}
            value={hobbySelectVal}
            allowClear
          />
        </div>
        <div className="filter_item">
          <div className="filter_type_tit">
            <Typography.Title level={5} style={{ margin: 0, fontWeight: 'normal' }}>
              <GlobalOutlined style={{ marginRight: 8 }} />
              按国家查找社区成员：
            </Typography.Title>
          </div>
          <Select
            showSearch
            style={{ flex: 1 }}
            placeholder="请选择国家"
            fieldNames={{ label: 'cname', value: 'cname' }}
            filterOption
            options={countriesData}
            onChange={countriesChange}
            allowClear
          />
        </div>
      </div>
      <Spin tip="正在玩命加载..." size="large" spinning={listLoading}>
        <div className="data_wrapper">
          {userList.map((item) => (
            <FeedUser
              avatar={item.avatar}
              nickName={item.nickName}
              userId={item.userId}
              tags={item.tags}
              key={item.userId}
            />
          ))}
        </div>
      </Spin>
      <div className="pagination_wrapper">
        {listTotal !== 0 && (
          <Pagination
            current={searchTourQuery.pageNum}
            total={listTotal}
            showTitle
            pageSize={searchTourQuery.pageSize}
            showSizeChanger={false}
            onChange={handleChangePage}
          />
        )}
        {!listLoading && listTotal === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
      </div>
    </div>
  );
  const contentPanel2 = (
    <div>
      <Spin tip="正在玩命加载..." size="large" spinning={actListLoading}>
        <div className="act_wrapper">
          {activityListData.map((item) => (
            <Activity
              key={item.id}
              id={item.id}
              country={item.country}
              remark={item.describes}
              userInfo={item.user}
              imgUrl={item.imgUrl}
              title={item.title}
              tags={item.tags}
              city={item.city}
            />
          ))}
        </div>
      </Spin>
      <div className="pagination_wrapper">
        {activityTotal !== 0 && (
          <Pagination
            current={searchActivityQuery.pageNum}
            total={activityTotal}
            showTitle
            pageSize={searchActivityQuery.pageSize}
            showSizeChanger={false}
            onChange={handleChangePageAct}
          />
        )}
        {!actListLoading && activityTotal === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
      </div>
    </div>
  );
  return (
    <Layouts>
      <div className="tab_wrapper">
        <Tabs
          defaultActiveKey="1"
          onChange={onChange}
          items={[
            {
              label: (
                <span>
                  <UserOutlined />
                  社区成员
                </span>
              ),
              key: '1',
              children: contentPanel1,
            },
            {
              label: (
                <span>
                  <CarOutlined />
                  社区活动
                </span>
              ),
              key: '2',
              children: contentPanel2,
            },
          ]}
        />
      </div>
    </Layouts>
  );
};
export default Feed;
